﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WLFramework.DataAccess;
using WLFramework.Json;

namespace SampleSite.admin.ajax
{
    /// <summary>
    /// getOrg 的摘要说明
    /// </summary>
    public class getOrg : AjaxHttpHandler
    {
        private class Org
        {
            public int id { get; set; }
            public string name { get; set; }
            public string ename { get; set; }
            public List<Org> children { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            PermissionCommand command = DataAccessor.CreateInstance<PermissionCommand>();
            var list = command.SYS_GetOrg().Where(k=>k.O_State!=2).ToList();

            List<Org> nodes = new List<Org>();
            int depths = list.Max(k => k.Depth) + 1;
            Dictionary<int, Org> parents = null;
            Dictionary<int, Org> currents = null;
            for (int i = 0; i < depths; i++)
            {
                int j = 0;
                currents = new Dictionary<int, Org>();
                while (j < list.Count)
                {
                    if (i == list[j].Depth)
                    {
                        Org node = new Org()
                        {
                            id = list[j].O_ID,
                            name = list[j].O_CName,
                            ename = list[j].O_EName,
                            children = new List<Org>()
                        };

                        if (list[j].Depth == 0)
                        {
                            nodes.Add(node);
                        }

                        currents[node.id] = node;

                        if (list[j].O_ParentID > 0 &&
                            parents != null &&
                            parents.ContainsKey(list[j].O_ParentID.Value))
                        {
                            parents[list[j].O_ParentID.Value].children.Add(node);
                        }

                        list.RemoveAt(j);
                    }
                    else
                    {
                        j++;
                    }
                }

                parents = currents;
                currents = null;
            }

            context.Response.Write(JSON.Instance.ToJSON(nodes));
        }
    }
}